//
//  RegistrationRecordsController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/4/20.
//  Copyright © 2020 QDSG. All rights reserved.
//

import UIKit

class RegistrationRecordsController: BaseViewController {
    
    var viewModel: RegistRecordViewModel? {
        didSet {
            tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "预约挂号记录"
        setUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NotiName.loginSuccess, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    func setUI() {
        tableView.tableFooterView = UIView()
        tableView.rowHeight = 114
        tableView.register(RegistrationRecordsCell.nibForCell(),
                           forCellReuseIdentifier: RegistrationRecordsCell.reuseIdentifier())
        tableView.mj_header = refreshHeader(action: #selector(refresh))
        tableView.mj_header?.beginRefreshing()
    }
    
    @objc func refresh() {
        loadData()
    }
    
    @objc private func loginSuccess() {
        tableView.mj_header?.beginRefreshing()
    }
    
    func endRefresh() {
        tableView.mj_header?.endRefreshing()
    }
    
    func createAlert(vm: RegistRowViewModel) {
        let alert = UIAlertController(title: "确定取消预约吗？", message: "", preferredStyle: .alert)
        let confirmAction = UIAlertAction(title: "确定", style: .destructive) { (action) in
            self.cancelRegistration(vm: vm)
        }
        let cancelAction = UIAlertAction(title: "关闭", style: .default) { (action) in
            
        }
        alert.addAction(cancelAction)
        alert.addAction(confirmAction)
        self.present(alert, animated: true) {
            
        }
    }

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var headerNoticeView: RegistrationNoticeView! {
        didSet {
            headerNoticeView.tapClosure = {
                let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
                agreementView.show(type: .registrationRule)
            }
        }
    }
    
}

extension RegistrationRecordsController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel?.numberOfSection ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: RegistrationRecordsCell.reuseIdentifier(), for: indexPath) as! RegistrationRecordsCell
        if let vm = viewModel?.rowVm(indexPath: indexPath) {
            cell.updateData(vm: vm, indexPath: indexPath)
            cell.delegate = self
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 16
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let vm = viewModel?.rowVm(indexPath: indexPath) {
            let vc = RegistrationDetailController(registrationId: vm.outpId)
            vc.isFromRecord = true
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}

extension RegistrationRecordsController: RegistrationRecordsCellDelegate {
    func registrationRecordsCellCancelBtnAction(indexPath: IndexPath) {
        guard let rowVm = viewModel?.rowVm(indexPath: indexPath) else { return }
        createAlert(vm: rowVm)
    }
}

extension RegistrationRecordsController {
    func loadData() {
        RegistrationViewModel.getRegistrationRecord(success: { (models) in
            self.endRefresh()
            self.viewModel = RegistRecordViewModel(models: models)
        }) { (errorMsg) in
            self.endRefresh()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    func cancelRegistration(vm: RegistRowViewModel) {
        HUDTool.showActivity()
        RegistrationViewModel.cancelRegistration(scheduleId: vm.outpId) { (msg, code) in
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: msg)
            case .success:
                HUDTool.show(message: msg)
                self.loadData()
            }
        }
    }
}
